package cn.stylefeng.guns.modular.gridsystem.netty.ws;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGateway;
import cn.stylefeng.guns.modular.gridsystem.mqtt.MyMqttClient;
import cn.stylefeng.guns.modular.gridsystem.netty.entity.RealTime;
import cn.stylefeng.guns.modular.gridsystem.service.BizGatewayService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ssy
 * @date 2022/1/10 14:46
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class WebSocketChannelHanlder extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Resource
    private RealTime realTime;

    @Resource
    private MyMqttClient mqttClient;

    @Resource
    private BizGatewayService bizGatewayService;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame text) throws Exception {
        log.info("wsServer收到消息：{}", text.text());
        String msg = text.text();
        JSONObject parseObj = JSONUtil.parseObj(msg);
        Integer type = parseObj.getInt("type");
        HashMap<String, Object> hashMap = new HashMap<>();
        if (type == 1) {//开始、停止采集
            String channel = parseObj.getStr("channel");
            String gatewayCode = parseObj.getStr("gatewayCode");
            String mapCategory = parseObj.getStr("mapCategory");
            String cmd = parseObj.getStr("cmd");
            realTime.setChannel(channel);
            realTime.setMapCategory(mapCategory);
            realTime.setGatewayCode(gatewayCode);

            hashMap.put("GLOBAL_MODE", "ACTION");
            hashMap.put("GLOBAL_GROUPID", "admin");
            hashMap.put("GLOBAL_CLIENTID", gatewayCode);
            hashMap.put("ACTION_POWER", cmd); // ON OFF
            mqttClient.publish("CONTROL/" + gatewayCode, JSONUtil.toJsonPrettyStr(hashMap));

        } else if (type == 2) {//敏感度-基础文件
            String gatewayCode = parseObj.getStr("gatewayCode");
            String cmd = parseObj.getStr("cmd");

            String mapCategory = parseObj.getStr("mapCategory");
            realTime.setMapCategory(mapCategory);

            final BizGateway gateway = bizGatewayService.listByDeviceCode(gatewayCode);
            hashMap.put("device_id", gatewayCode);
            hashMap.put("action", cmd);

            final HashMap<String, Object> map = new HashMap<>();
            map.put("device_oper", hashMap);
            mqttClient.publish("similarityControl/" + gateway.getGatewayIp(), JSONUtil.toJsonPrettyStr(map));
        } else if (type == 3) {//敏感度-开始比对
            String gatewayCode = parseObj.getStr("gatewayCode");
            String mapCategory = parseObj.getStr("mapCategory");
            String channel = parseObj.getStr("channel");
            realTime.setChannel(channel);
            realTime.setMapCategory(mapCategory);

            final BizGateway gateway = bizGatewayService.listByDeviceCode(gatewayCode);
            hashMap.put("device_id", gatewayCode);
            hashMap.put("action", "similarity_start_contrast");

            final HashMap<String, Object> map = new HashMap<>();
            map.put("device_oper", hashMap);
            mqttClient.publish("similarityControl/" + gateway.getGatewayIp(), JSONUtil.toJsonPrettyStr(map));
        } else if (type == 4) {//敏感度-结束比对
            String gatewayCode = parseObj.getStr("gatewayCode");
            String mapCategory = parseObj.getStr("mapCategory");
            realTime.setMapCategory(mapCategory);

            final BizGateway gateway = bizGatewayService.listByDeviceCode(gatewayCode);
            hashMap.put("device_id", gatewayCode);
            hashMap.put("action", "similarity_stop_contrast");

            final HashMap<String, Object> map = new HashMap<>();
            map.put("device_oper", hashMap);
            mqttClient.publish("similarityControl/" + gateway.getGatewayIp(), JSONUtil.toJsonPrettyStr(map));
        } else if (type == 5) {//手动触发采集
            String gatewayCode = parseObj.getStr("gatewayCode");
            String duration = parseObj.getStr("duration");
            final BizGateway gateway = bizGatewayService.listByDeviceCode(gatewayCode);
            hashMap.put("device_id", gatewayCode);
            hashMap.put("action", "collect_voice_manual");

            HashMap<String, Object> map = new HashMap<>();
            map.put("start_time", DateUtil.date().getTime());
            map.put("duration", duration);
            hashMap.put("param", map);
            final HashMap<String, Object> map1 = new HashMap<>();
            map1.put("device_oper", hashMap);
            mqttClient.publish("deviceControl/" + gateway.getGatewayIp(), JSONUtil.toJsonPrettyStr(map1));
        } else if (type == 6) {//声压级校准
            float splOffset = parseObj.getFloat("splOffset");
            String gatewayCode = parseObj.getStr("gatewayCode");
            String cmd = parseObj.getStr("cmd");
            String channel = parseObj.getStr("channel");
            realTime.setGatewayCode(gatewayCode);
            realTime.setChannel(channel);
            realTime.setStandardSpl(splOffset);
            realTime.setSplCalibration(true);
            hashMap.put("GLOBAL_MODE", "ACTION");
            hashMap.put("GLOBAL_GROUPID", "admin");
            hashMap.put("GLOBAL_CLIENTID", gatewayCode);
            hashMap.put("ACTION_POWER", cmd);
            mqttClient.publish("CONTROL/" + gatewayCode, JSONUtil.toJsonPrettyStr(hashMap));
        } else if (type == 7) {//修改图谱
            String mapCategory = parseObj.getStr("mapCategory");
            String channel = parseObj.getStr("channel");
            realTime.setChannel(channel);
            realTime.setMapCategory(mapCategory);
        } else if (type == 8) {//超出阈值触发采集
            String mapCategory = parseObj.getStr("mapCategory");
            String channel = parseObj.getStr("channel");
            String gatewayCode = parseObj.getStr("gatewayCode");
            final BizGateway gateway = bizGatewayService.listByDeviceCode(gatewayCode);
            realTime.setGatewayCode(gatewayCode);
            realTime.setChannel(channel);
            realTime.setMapCategory(mapCategory);

            hashMap.put("device_id", gatewayCode);
            hashMap.put("action", "collect_voice_30s");
            HashMap<String, Object> map = new HashMap<>();
            map.put("device_oper", hashMap);
            mqttClient.publish("deviceControl/" + gateway.getGatewayIp(), JSONUtil.toJsonPrettyStr(map));
        } else if (type == 9) {//修改通道
            String mapCategory = parseObj.getStr("mapCategory");
            String channel = parseObj.getStr("channel");
            String gatewayCode = parseObj.getStr("gatewayCode");
            realTime.setGatewayCode(gatewayCode);
            realTime.setChannel(channel);
            realTime.setMapCategory(mapCategory);
        } else if (type == 10) {//是否开启降噪
            String mapCategory = parseObj.getStr("mapCategory");
            String channel = parseObj.getStr("channel");
            String gatewayCode = parseObj.getStr("gatewayCode");
            Boolean isNoise = parseObj.getBool("isNoise");
            realTime.setNoise(isNoise);
            realTime.setGatewayCode(gatewayCode);
            realTime.setChannel(channel);
            realTime.setMapCategory(mapCategory);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端建立连接，通道开启！");
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
        MyChannelHandlerPool.sendMessage(ctx, JSONUtil.toJsonStr(realTime));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端断开连接，通道关闭！");
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.channel().close();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
    }

    private static Map getUrlParams(String url) {
        Map<String, String> map = new HashMap<>();
        url = url.replace("?", ";");
        if (!url.contains(";")) {
            return map;
        }
        if (url.split(";").length > 0) {
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr) {
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key, value);
            }
            return map;

        } else {
            return map;
        }
    }

}
